<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;

/**
 * 老师管理
 *
 * @icon fa fa-circle-o
 */
class Teacher extends Backend
{

    /**
     * Teacher模型对象
     * @var \app\admin\model\Teacher
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Teacher;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        // $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        // $table = $this->model->getQuery()->getTable();
        // $database = \think\Config::get('database.database');
        // $fieldArr = [];
        // $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        // foreach ($list as $k => $v) {
        //     if ($importHeadType == 'comment') {
        //         $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
        //     } else {
        //         $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
        //     }
        // }
        $fields = [
            "name",//姓名
            "subject",//学科
            "marital_status",//婚姻状况
            "home_address",//家庭住址
            "department",//学部
            "gender",//性别
            "id_number",//身份证号
            "age",//年龄
            "mobile",//联系电话
            "native_place",//籍贯
            "birth",//出生日期
            "nation",//民族
            "working_time",//参加工作时间
            "working_years",//工龄
            "political_face",//政治面目
            "education",//学历
            "academic_degree",//学位
            "major",//专业
            "school",//毕业院校
            "qualification",//教师资格
            "title",//职称
            "teaching_subject",//任教科目
            "personnel_category",//人员类别
            "first_degree",//第一学历
            "first_degree_school",//第一学历毕业学校及专业
            "highest_education",//最高学历
            "highest_education_school",//最高学历毕业学校
            "highest_education_major",//最高学历所学专业
            "working_time_sz",//深圳任教起始时间
            "registered_residence",//户籍
            "three_projects",//三名工程评选情况
            "future_educators",//入选未来教育家情况（如无，则不填）
            "professional_competition",//专业技能大赛
            "normal_student",//是否师范生
            "personnel_source",//人员来源
            "entry_time",//进入本单位时间
            "leave_time",//离开本单位时间
            "emergency_contact",//紧急联系人
            "relationship",//紧急联系人关系
            "emergency_contact_mobile",//紧急联系号码
        ];
          


         

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            // $fields = [];
            // for ($currentRow = 3; $currentRow <= 3; $currentRow++) {
            //     for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
            //         $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
            //         $fields[] = $val;
            //     }
            // }
            
            for ($currentRow = 4; $currentRow <= $allRow; $currentRow++) {
                $row = [];
                $mobileK = '';
                foreach ($fields as $key => $value) {
                    $val = $currentSheet->getCellByColumnAndRow($key+2, $currentRow)->getValue();
                    if (substr($val,0,1) == '=') {
                        $val = $currentSheet->getCellByColumnAndRow($key+2, $currentRow)->getCalculatedValue();
                    }
                    if ($value == 'mobile') {
                        $mobileK = $val = trim($val);
                    }
                    $row[$value] = is_null($val) ? '' : $val;
                }
                // 如果手机号存在就修改
                $one = $this->model->where(['mobile'=>$mobileK])->find();
                if ($one) {
                    $one->where(['mobile'=>$mobileK])->update($row);
                    continue ;
                }
                // for ($currentColumn = 2; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                //     $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                //     $values[] = is_null($val) ? '' : $val;
                // }
                // $row = [];
                
                // $temp = array_combine($fields, $values);
                // foreach ($temp as $k => $v) {
                //     if (isset($fieldArr[$k]) && $k !== '') {
                //         $row[$fieldArr[$k]] = $v;
                //     }
                // }
                // if ($row) {
                    $insert[$mobileK] = $row;
                // }
                // var_dump($temp);exit;
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            // $has_admin_id = false;
            // foreach ($fieldArr as $name => $key) {
            //     if ($key == 'admin_id') {
            //         $has_admin_id = true;
            //         break;
            //     }
            // }
            // if ($has_admin_id) {
            //     $auth = Auth::instance();
            //     foreach ($insert as &$val) {
            //         if (!isset($val['admin_id']) || empty($val['admin_id'])) {
            //             $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
            //         }
            //     }
            // }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function auth($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $mobiles = \app\admin\model\User::alias('u')
                ->field('`up`.`mobile`,`up`.`id`,`up`.`nickname`,`ut`.`is_all`')
                ->where('u.mobile',$row->mobile)
                ->join(['fa_user_teacher'=>'ut'],'ut.pmobile = u.mobile','left')
                ->join(['fa_user'=>'up'],'ut.mobile = up.mobile','right')
                // ->fetchSql(true)
                ->select();
                // ->column('`up`.`mobile`');
            // var_dump($mobiles);exit;
            $row->auth = implode(',',array_column($mobiles,'mobile') );
            $row->is_all = !empty($mobiles)?$mobiles[0]['is_all']:0;
            // var_dump($row['auth']);exit;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $mobiles = \app\admin\model\User::alias('u')
                ->where('u.mobile',$row->mobile)
                ->find();
        if (empty($mobiles)) {
            $this->error(__('企业微信找不到：'.$row->name, ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $result = (new \app\common\model\UserTeacher)->auth($row->mobile,$params);
            // $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
